﻿namespace MicroCloud.AspNetCore
{
    /// <summary>
    /// Json技术异常处理中间件
    /// </summary>
    public class JsonExceptionHandlerMiddleware : IMiddleware
    {
        //字段
        private readonly RequestDelegate _next;
        private readonly ILogger<JsonExceptionHandlerMiddleware> _logger;

        #region "构造函数"
        #region "初始化一个Json技术异常处理中间件的新实例"
        /// <summary>
        /// 初始化一个Json技术异常处理中间件 <see cref="JsonExceptionHandlerMiddleware"/> 的新实例
        /// </summary>
        /// <param name="next"></param>
        /// <param name="loggerFactory"></param>
        public JsonExceptionHandlerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<JsonExceptionHandlerMiddleware>();
        }
        #endregion

        #endregion

        #region "方法"
        #region "执行中间件拦截逻辑"
        /// <summary>
        /// 执行中间件拦截逻辑
        /// </summary>
        /// <param name="context">Http上下文</param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(new EventId(), ex, ex.Message);
                if (context.Request.IsAjaxRequest() || context.Request.IsJsonContextType())
                {
                    if (context.Response.HasStarted)
                    {
                        return;
                    }
                    context.Response.Clear();
                    context.Response.StatusCode = 200;
                    context.Response.ContentType = "application/json; charset=utf-8";
                    await context.Response.WriteAsync(AjaxResult.Error(ex.Message).ToJsonString());
                    return;
                }
                throw;
            }
        }
        #endregion

        #endregion

    }

}
